/*
 * Copyright (C) 2013 Buptcoder
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.buptcoder.wifimap.wifiinfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.buptcoder.wifimap.Utils.Constants;
import com.buptcoder.wifimap.Utils.MapLog;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;

public class WifiLocationInfoGetter {

    private static String TAG = "WifiLocationInfoGetter";
    private static WifiLocationInfoGetter mInstance;
    private Context mContext;

    public synchronized static WifiLocationInfoGetter getInstance(
            Context context) {
        if (mInstance == null) {
            mInstance = new WifiLocationInfoGetter(context);
        }
        return mInstance;
    }

    private WifiLocationInfoGetter(Context context) {
        mContext = context;
    }

    public synchronized List<WifiAccessPointInfo> getAllAPInfo() {
        List<WifiAccessPointInfo> allAPList = Collections
                .synchronizedList(new ArrayList<WifiAccessPointInfo>());
        ContentResolver resolve = mContext.getContentResolver();
        Cursor cursor = null;
        try {
            cursor = resolve.query(Constants.WIFI_APINFO_URL,
                    Constants.getWifiProjection(), null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    WifiAccessPointInfo info = new WifiAccessPointInfo();
                    info.setSSID(cursor.getString(Constants.PROJECT_INDEX.SSID
                            .getIndex()));
                    info.setLantitude(cursor
                            .getDouble(Constants.PROJECT_INDEX.LAT.getIndex()));
                    info.setLongitude(cursor
                            .getDouble(Constants.PROJECT_INDEX.LON.getIndex()));
                    info.setType(cursor.getInt(Constants.PROJECT_INDEX.TYPE
                            .getIndex()));
                    info.setUpdateDate(cursor
                            .getLong(Constants.PROJECT_INDEX.UPDATE.getIndex()));
                    allAPList.add(info);
                }
            }
        } catch (Exception e) {
            MapLog.d(TAG, "error: " + e.toString());
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return allAPList;
    }
}
